package middleware

import (
	"gitee.com/baal1990/epidemic/global"
	response "gitee.com/baal1990/epidemic/model/common/response_dfitc"
	"gitee.com/baal1990/epidemic/model/epidemic"
	"gitee.com/baal1990/epidemic/service"
	"gitee.com/baal1990/epidemic/utils/token"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
		xToken := c.Request.Header.Get("x-token")
		if xToken == "" {
			global.GVA_LOG.Sugar().Error("非法header")
			response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)
			c.Abort()
			return
		}
		t := token.Token{AccessToken: xToken}
		payload, err := t.ValidateAccessToken()
		if err != nil {
			global.GVA_LOG.Sugar().Error("非法x-token", err)
			response.FailWithDetailedWithErrorCode(response.ERROR_TOKEN_EXPIRED, nil, "token已过期", c)
			c.Abort()
			return
		}
		id, err := strconv.Atoi(payload.UserId)
		if err != nil {
			global.GVA_LOG.Sugar().Error("非法id")
			response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)
			c.Abort()
			return
		}
		var epidemicUserService = service.ServiceGroupApp.EpidemicServiceGroup.EpidemicUserService
		// 手机端查询用户信息特殊处理，仅校验token有效性，不校验是否已通过审核
		if c.Request.URL.Path == "/epidemic_mobile/user/find" || c.Request.URL.Path == "/epidemic/user/dict" ||
			c.Request.URL.Path == "/epidemic_mobile/user/edit" {
			userInfo, err := epidemicUserService.GetEpidemicUserAny(id)
			if err != nil {
				global.GVA_LOG.Sugar().Error("查找用户信息失败", err)
				response.FailWithDetailedWithErrorCode(response.ERROR_NO_USER, gin.H{"reload": true}, "未登录或非法访问", c)
				c.Abort()
				return
			}
			c.Set("OPERATION_USER_INFO", userInfo)
		} else {
			userInfo, err := epidemicUserService.GetEpidemicUserEnable(id)
			if err != nil {
				global.GVA_LOG.Sugar().Error("查找用户信息失败", err)
				response.FailWithDetailedWithErrorCode(response.ERROR_NO_USER, gin.H{"reload": true}, "未登录或非法访问", c)
				c.Abort()
				return
			}
			c.Set("OPERATION_USER_INFO", userInfo)
		}
		c.Next()
	}

}

// IsManager 管理员身份校验
func IsManager() gin.HandlerFunc {
	return func(c *gin.Context) {
		user := c.MustGet("OPERATION_USER_INFO").(epidemic.EpidemicUser)
		if user.Role != global.DICT_ROLES_SUPER && user.Role != global.DICT_ROLES_MANAGER {
			global.GVA_LOG.Sugar().Error("非管理账号")
			response.FailWithDetailedWithErrorCode(response.USER_ROLES_ERR, nil, "账号权限不足", c)
			c.Abort()
		} else {
			c.Next()
		}
	}
}
